import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { combineReducers } from 'redux';
import {
  Store,
  compose,
  createStore,
  applyMiddleware
} from 'redux';

import {
  Provider, connect
} from 'react-redux';

import {
  Map,
  List
} from 'immutable';

import thunkMiddleware from 'redux-thunk';
import TopPanel from "components/topPanel";
import LeftPanel from "components/leftPanel";
import Tab from "components/tab";
import * as actions from 'actions';
import tabReducer from "reducers/tab";

require('es6-object-assign').polyfill();
var styles = require('./index.less');


class App extends React.PureComponent<any, any> {
  constructor(props, context) {
    super(props, context);
  }

  static childContextTypes = {
    addTabPage: React.PropTypes.func,
    selectTabPage: React.PropTypes.func,
    deleteTabPage: React.PropTypes.func
  }

  getChildContext() {
    return {
      addTabPage: (title: string, url: string) => {
        this.props.dispatch(actions.addTabPage(title, url))
      },

      selectTabPage: (title: string) => {
        this.props.dispatch(actions.selectTabPage(title))
      },

      deleteTabPage: (title: string) => {
        this.props.dispatch(actions.deleteTabPage(title))
      }
    }
  }

  render() {
    const { tabConfigs } = this.props;
    return (
      <div>
        <TopPanel></TopPanel>
        <div className="layout-main" style={{}}>
          <LeftPanel></LeftPanel>
          <div style={{ marginLeft: '85px', height: '100%' }}>
            <Tab tabConfigs={tabConfigs}></Tab>
          </div>
        </div>
      </div>);
  }
}

function mapStateToProps(state) {
  const props = {
    tabConfigs: state.tab
  };
  return props;
}

const AppContainer = connect(mapStateToProps)(App);

$(function () {
  const reducers = combineReducers({
    tab: tabReducer
  });

  const initState = {
    tab: Map({
      selectTitle: "首页",
      list: List([{
        title: "首页",
        url: "/desktop-admin.html",
        deletable: false,
      }])
    })
  }

  const middleware = applyMiddleware(thunkMiddleware);
  const store = compose(middleware)(createStore)(reducers, initState);

  window.addTabPage = function (title, url) {
    console.log("addTabPage", url)
    store.dispatch(actions.addTabPage(title, url));
  }

  ReactDOM.render(
    <Provider store={store} >
      <AppContainer></AppContainer>
    </Provider>, document.getElementById('content')
  );
})